package com.ag.admin.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ag.admin.utils.UserUtil;

/**
 * 系统用户访问过滤器
 * 
 * @author 黎肇明
 * 
 */

public class AccessFilter implements Filter {

	private String[] excludeURL;

	@Override
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		try {
			/**
			 * 如果处理HTTP请求，并且需要访问诸如getHeader或getCookies等在ServletRequest中无法得到的
			 * 方法，就要把此request对象构造成HttpServletRequest
			 */
			HttpServletRequest request = (HttpServletRequest) servletRequest;
			HttpServletResponse response = (HttpServletResponse) servletResponse;
			String currentURL = request.getRequestURI(); // 取得根目录所对应的绝对路径
			String targetURL = currentURL.substring(currentURL.indexOf("/", 1),
					currentURL.length()); // 截取到当前文件名用于比较
			HttpSession session = request.getSession(false);
			if (!isHave(excludeURL, targetURL)) {
				// 判断当前页是否是重定向以后的登录页面，如果是就不做session的判断，防止出现死循环
				if (session == null
						|| session.getAttribute(UserUtil.USER_SESSION) == null) {
					// 用户登录以后需要手动添加session
					response.sendRedirect(request.getContextPath()
							+ excludeURL[0]);
					// 如果session为空，表示用户没有登录就重定向到配置的第一个页面
					return;
				}
			}
			// 加入filter链继续向下执行
			filterChain.doFilter(request, response);
			/**
			 * 调用FilterChain对象的doFilter方法。Filter接口的doFilter方法取一个FilterChain对象作
			 * 为它的一个参数。在调用此对象的doFilter方法时，激活下一个相关的过滤器。如果没有另一个
			 * 过滤器与servlet或JSP页面关联，则servlet或JSP页面被激活。
			 */

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String cfgStr = filterConfig.getInitParameter("excludeURL");
		if (cfgStr == null || cfgStr.trim().equals("")) {
			excludeURL = new String[2];
			excludeURL[1] = "/login.jsp";
			excludeURL[2] = "/admin/LoginOut_checkLogin.action";
		} else {
			excludeURL = cfgStr.split(",");
		}
	}

	@Override
	public void destroy() {
		excludeURL = null;
	}

	private boolean isHave(String[] origin, String dest) {
		for (String str : origin) {
			if (str.indexOf(dest) != -1) {
				return true;
			}
		}
		return false;
	}
}
